﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Threading;
using SMSAssistant.Model;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;

namespace SMSAssistant
{
    public class EmojiManager
    {
        private const string IMAGEPATH = "/Images/Emoji/";
        private const string EMOJIXMLFILE = "EMOJI.xml";

        public event EventHandler EmojiLoaded;

        bool isLoaded;

        public bool IsLoaded
        {
            get
            {
                return isLoaded;
            }
            set
            {
                isLoaded = value;
            }
        }

        List<Emoji> emojiList;

        public List<Emoji> EmojiList
        {
            get
            {
                return emojiList;
            }
            set
            {
                emojiList = value;
            }
        }

        static EmojiManager instance;
        public static EmojiManager Instance
        {
            get
            {
                if (instance == null)
                    instance = new EmojiManager();
                return instance;
            }
        }

        private EmojiManager()
        {

        }

        private void LoadEmoji()
        {
            try
            {
                XDocument doc = XDocument.Load(EMOJIXMLFILE);

                var emojis = from emoji in doc.Root.Elements("Item")
                             select new Emoji
                                 (Convert.ToInt32(emoji.Element("id").Value),
                                    IMAGEPATH + emoji.Element("Image").Value,
                                  emoji.Element("Tag").Value,
                                  emoji.Element("Name").Value
                               );
                             
                List<Emoji> list = emojis.ToList();

                //foreach(var e in emojis)
                //{
                //    list.Add(e);
                //    Thread.Sleep(20);
                //}

                Deployment.Current.Dispatcher.BeginInvoke(new Action<List<Emoji>>((l) =>
                {
                    EmojiList = l;
                    if (EmojiLoaded != null)
                    {
                        EmojiLoaded(this, new EventArgs());
                    }
                }), list);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }

        internal void Load()
        {
            ThreadPool.QueueUserWorkItem(
              (o) =>
              {
                  LoadEmoji();
              }, null);
        }
    }
}
